package des;
import java.sql.*;

/**
 * @author 刘正星
 * @version 1.0.0
 * @ClassName MySqlConnBean.java
 * @Description TODO
 * @createTime 2020年11月08日 21:50:00
 */
public class MySqlConnBean {
    private Statement stmt = null;
    private Connection conn = null;
    ResultSet rs = null;
    // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
    //static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    //static final String DB_URL = "jdbc:mysql://localhost:3306/test";
    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";

    //构造函数
    public MySqlConnBean() {
    }

    public void OpenConn(String user, String pwd, String dbName, String adress) throws Exception {
        String DB_URL = "jdbc:mysql://" + adress + ":3306/" + dbName + "?useSSL=false&serverTimezone=UTC";

        try {
            Class.forName(JDBC_DRIVER);
            //这里改成自己的数据库账户
            //改成自己的数据库密码

            conn = DriverManager.getConnection(DB_URL, user, pwd);
            stmt = conn.createStatement();
        } catch (SQLException e) {
            System.err.println("Data.executeQuery: " + e.getMessage());
        }
    }

    //执行查询类的SQL语句，有返回集
    public ResultSet executeQuery(String sql) {
        rs = null;
        try {
            stmt = conn.createStatement(
                    ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            rs = stmt.executeQuery(sql);
        } catch (SQLException e) {
            System.err.println("Data.executeQuery: " + e.getMessage());
        }
        return rs;
    }

    public boolean execute(String sql) throws SQLException {
        if (stmt == null) {
            stmt = conn.createStatement();
        }
        boolean result = stmt.execute(sql);
        return result;
    }

    //关闭对象
    public void closeStmt() {
        try {
            stmt.close();
        } catch (SQLException e) {
            System.err.println("Date.executeQuery: " + e.getMessage());
        }
    }

    public void closeConn() {
        try {
            conn.close();
        } catch (SQLException e) {
            System.err.println("Data.executeQuery: " + e.getMessage());
        }
    }
}